package com.bidevalution.controller.task;

import com.bidevalution.business.common.RedisKeys;
import com.bidevalution.business.dto.WebSocketSendTimeKeyDto;
import com.bidevalution.support.context.ChannelContext;
import com.bidevalution.support.context.ResponseObject;
import com.bidevalution.support.factory.WebSocketService;
import com.bidevalution.support.websocket.WebSocketCached;
import com.qtp.core.redis.RedisUtil;
import com.qtp.core.util.GsonUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Map;

/**
 * webscoket补发信息
 */
@Component
@Log4j2
public class WebSocketSendTask {
    @Autowired
    private WebSocketService webSocketService;

    /**
     * 3秒检查执行一次
     *
     * @throws Exception
     */
    @Scheduled(cron = "*/3 * *  * * * ")
    public void sendTask() throws Exception {
        log.debug("WebScoket 定时发送器......");
        Map<String, String> values = RedisUtil.getAllMap(RedisKeys.WebSocketSendTime.name());
        long now = System.currentTimeMillis();
        long expTime = RedisKeys.WebSocketSendTime.expireSecond * 1000;
        for (Map.Entry<String, String> e: values.entrySet()) {
            WebSocketSendTimeKeyDto webSocketSendTimeKeyDto = WebSocketSendTimeKeyDto.parse(e.getKey());
            Map map = GsonUtil.jsonToMapWithGson(e.getValue());
            ResponseObject value = new ResponseObject();
            value.putAll(map);
            value.delTodoList();
            if (value.getTimestamp() == null || now - value.getTimestamp() > expTime) {
                continue;
            }
            ChannelContext channelContext = WebSocketCached.getExpertChannelContextMap().get(webSocketSendTimeKeyDto.getChandId());
            if (channelContext != null) {
                webSocketService.send(channelContext, value);
            }
        }
    }

}
